package com.hxh.spring.cloud.emoticon.produce.thread;

import com.alibaba.fastjson.JSONObject;
import com.hxh.spring.cloud.emoticon.produce.dto.ResultBean;
import com.hxh.spring.cloud.emoticon.produce.entity.Emoticon;
import com.hxh.spring.cloud.emoticon.produce.utils.HttpUtil;
import com.hxh.spring.cloud.emoticon.produce.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.Collectors;

/**
 * @author huangxunhui
 * Date: Created in 2019-05-09 17:52
 * Utils: Intellij Idea
 * Description:
 */
@Slf4j
public class ProduceThread implements Runnable {

    private RedisUtil<String> redisUtil;

    private ConcurrentLinkedQueue<String> queue;

    private String url = "http://api.emoji100.com/?a=doutu&ver=0.9&c=emoji&appname=box_android&pt=";

    public ProduceThread(RedisUtil<String> redisUtil, ConcurrentLinkedQueue<String> queue) {
        this.redisUtil = redisUtil;
        this.queue = queue;
    }

    private static final String URL = "http://api.emoji100.com/";

    @Override
    public void run() {

        Map<String,String > param = new HashMap<>(4);
        param.put("a","doutu");
        param.put("ver","0.9");
        param.put("c","emoji");
        param.put("appname","box_android");

        String pt = queue.poll();
        pt = pt == null ? "" : pt;
        param.put("pt", pt);

        String responseData = HttpUtil.get(URL, param);
        if(responseData == null){
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(responseData);
        Object data = jsonObject.get("data");
        List<ResultBean> resultBeans = JSONObject.parseArray(data.toString(), ResultBean.class);

        // 数据入队
        queue.offer(resultBeans.get(resultBeans.size() - 1).getPTime());

        // 记录URL和数量
        new SaveUrlThread(redisUtil,url+pt+"/"+ resultBeans.size()).run();
    }

}
